package com.freedy.concurrent.Monitors.patterns;

import lombok.extern.slf4j.Slf4j;

/**
 * 多任务版保护性暂停
 * Consumer->Producer必须一一对应
 * @author Freedy
 * @date 2021/4/22 13:40
 */
public class MultiGuardedSuspension {
    public static void main(String[] args) throws Exception {
        for (int i = 1; i <= 3; i++) {
            new Consumer("消费者"+i).start();
        }
        Thread.sleep(1000);
        for (Long id : MailBox.getIds()) {
            new Producer("生产者"+id,id,id+"🆗okkkkkkkkkkk！！！！！").start();
            System.in.read();
        }
    }
}
@Slf4j(topic = "Consumer")
class Consumer extends Thread{
    private final Guarded guarded;

    public Consumer(String name) {
        super(name);
        guarded = MailBox.createGuarded();
    }

    public long getId() {
       return guarded.getId();
    }

    @Override
    public void run() {
        log.info("消费 id:{}",guarded.getId());
        Object o = guarded.get();
        log.info("消费结果:{}", o);
    }
}

@Slf4j(topic = "Producer")
class Producer extends Thread{
    private final long id;
    private final Object content;

    public Producer(String name,long id, Object content) {
        super(name);
        this.id = id;
        this.content = content;
    }

    @Override
    public void run() {
        Guarded guarded = MailBox.getGuarded(id);
        log.info("给id:{}生产",id);
        guarded.complete(content);
        log.info("----------生产完成----------");
    }
}